package com.kyh.service.sys.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.kyh.service.sys.DictService;
import com.kyh.sys.entity.Dict;
import com.kyh.sys.mapper.DictMapper;
import com.kyh.vo.BootstrapTableVoJA;
import com.kyh.vo.R;

@Service("dictService")
public class DictServiceImpl implements DictService {

	@Autowired
	private DictMapper dictMapper;

	@Override
	@Transactional
	public R add(Dict entity) throws Exception {
		
		// 添加数据
		if (dictMapper.insert(entity) != 1) {
			throw new RuntimeException("失败");
		}
		
		return R.ok();
	}

	@Override
	@Transactional
	public R deleteFalse(Long dictId) throws Exception {
	
		if (dictMapper.deleteFalse(dictId) != 1) {
			throw new RuntimeException("失败");
		}
		
		return R.ok();
	}

	@Override
	@Transactional
	public R deleteTrue(Long dictId) {
		
		Dict entity = dictMapper.get(dictId);
		if (entity == null) {
			return R.error("该数据不存在");
		}
		
		dictMapper.deleteTrue(dictId);
		
		return R.ok();
	}

	@Override
	@Transactional
	public R edit(Dict entity) throws Exception {
		
		// 更新数据
		if (dictMapper.update(entity) != 1) {
			throw new RuntimeException("失败");
		}
		
		return R.ok();
	}

	@Override
	public BootstrapTableVoJA search(Dict cond) {
		
		List<Map<String, Object>> listMap = cond.queryMap();
		
		int total = cond.count();
		
        BootstrapTableVoJA vo = new BootstrapTableVoJA();
        vo.setRowsByListMap(listMap);
        vo.setTotal(total);
        
        return vo;
	}

	@Override
	public R tree(String dictKey) {

		JSONArray JANodes1 = new JSONArray();
//		ConfDict con1 = new ConfDict();
//		con1.e.setDictKey(dictKey);
//		List<Dict> listNodes1 = dictMapper.search(con1);
		List<Dict> listNodes1 = new Dict().setDictKey(dictKey).queryList();
		
		for (Dict node1 : listNodes1) {
			
			JANodes1.add(node1.tree());
		}

        return R.ok(JANodes1);
	}
}
